using System;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Text;

namespace WIT.Global;

/// <summary>
/// 本地日志帮助类
/// </summary>
public static class LocalLog
{
	private static readonly string ROOT = AppDomain.CurrentDomain.BaseDirectory;

	private static readonly string FOLDER = "log";

	/// <summary>
	/// 记录日志
	/// </summary>
	/// <param name="content"></param>
	/// <param name="logType">日志类型</param>
	public static void Log(string content, string logType = "log")
	{
		try
		{
			string text = ROOT + FOLDER + "\\" + logType;
			if (!Directory.Exists(text))
			{
				Directory.CreateDirectory(text);
			}
			StreamWriter streamWriter = new StreamWriter(new FileStream(text + "\\" + logType + DateTime.Now.ToString("yyyyMMdd") + ".log", FileMode.Append, FileAccess.Write, FileShare.ReadWrite), Encoding.Default);
			streamWriter.WriteLine(" ----- " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " ----- ");
			streamWriter.WriteLine(content);
			streamWriter.Flush();
			streamWriter.Close();
		}
		catch (Exception ex)
		{
			throw new Exception(ex.Message);
		}
	}

	/// <summary>
	/// 记录try..catch..捕获的异常信息（会记录下捕获异常的类名+方法名）
	/// </summary>
	/// <param name="content">exception</param>
	public static void Error(string content)
	{
		try
		{
			string text = "exception";
			string text2 = ROOT + FOLDER + "\\" + text;
			if (!Directory.Exists(text2))
			{
				Directory.CreateDirectory(text2);
			}
			string path = text2 + "\\" + text + DateTime.Now.ToString("yyyyMMdd") + ".log";
			MethodBase method = new StackTrace(fNeedFileInfo: true).GetFrame(1).GetMethod();
			StreamWriter streamWriter = new StreamWriter(new FileStream(path, FileMode.Append, FileAccess.Write, FileShare.ReadWrite), Encoding.Default);
			streamWriter.WriteLine(" ----- " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " -----  " + method.DeclaringType.FullName + "." + method.Name);
			streamWriter.WriteLine(content);
			streamWriter.Flush();
			streamWriter.Close();
		}
		catch (Exception ex)
		{
			throw new Exception(ex.Message);
		}
	}
}
